package com.ecarx.module_udisk;

import com.ecarx.library_base.base_util.NotifyListener;
import com.ecarx.library_base.scoket.SocketManager;
import com.ecarx.library_base.scoket.callback.MsgCallback;
import com.ecarx.library_base.scoket.callback.Packetlistener;
import com.google.gson.JsonObject;

import org.json.JSONException;
import org.json.JSONObject;

public class UdiskUpdateSocketManager {
    private SocketManager mSocketManager;
    private SocketManager.ServerOS mHypervisorOs;
    private static final int QUERT_STATUS_MSGID = 2000;

    public UdiskUpdateSocketManager() {
        mSocketManager = SocketManager.get();
        mHypervisorOs = SocketManager.ServerOS.Hypervisor_Update_OS;

    }

    public void connect(NotifyListener listener) {
        mSocketManager.connectServer(mHypervisorOs);
        mSocketManager.registerCallback(mHypervisorOs, new MsgCallback() {
            @Override
            public void onConnected() {
                listener.onNotify(1, null);
            }

            @Override
            public void onDisConnected() {

            }

            @Override
            public void onConnectFail() {
                listener.onNotify(0, null);
            }

            @Override
            public void onReceiver(int msgId, String msg) {
                listener.onNotify(msgId, msg);
            }

            @Override
            public void onFail(String reason) {
                listener.onNotify(0, reason);
            }
        });
    }

    public boolean isConnect() {
        return mSocketManager.isConnected(mHypervisorOs);
    }

    public void queryUpdateStatus(NotifyListener listener) {
        mSocketManager.sendRequest(mHypervisorOs, getCommonJson(QUERT_STATUS_MSGID).toString(), new Packetlistener(3000) {
            @Override
            public void onTimeout() {

            }

            @Override
            public void onSuccess(int msgId, String response) {
                listener.onNotify(msgId,response);
            }

            @Override
            public void onFail(int code, String reason) {

            }
        });
    }

    private JSONObject getCommonJson(int msgId){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("msgId",msgId);
            jsonObject.put("seq",System.currentTimeMillis());
            jsonObject.put("version","1.0.0");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return jsonObject;
    }
}
